﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Web;

namespace VI.Chat.VIChatControl
{
    internal class ChatManager
    {
        private ApplicationWrapper _application;
        public ApplicationWrapper CurrentApplication
        {
            get
            {
                if (_application == null)
                {
                    _application = new ApplicationWrapper(HttpContext.Current.Application);
                }
                return _application;
            }
            set
            {
                _application = value;
            }
        }

        private SessionWrapper _session;
        public SessionWrapper CurrentSession
        {
            get
            {
                if (_session == null)
                {
                    _session = new SessionWrapper(HttpContext.Current.Session);
                }
                return _session;
            }
            set
            {
                _session = value;
            }
        }

        public void ActivateUser(string user)
        {
            if (!CurrentApplication.OnlineUsers.Contains(user))
                CurrentApplication.OnlineUsers.Add(user);
            CurrentSession.User = user;
        }

        public void DeactivateUser(string user)
        {
            if (CurrentApplication.OnlineUsers.Contains(user))
                CurrentApplication.OnlineUsers.Remove(user);
            CurrentSession.User = "";
        }

        public IList<string> ActiveUserList
        {
            get
            {
                return CurrentApplication.OnlineUsers;
            }
        }

        public void SendMessage(string toUser, string message)
        {
            string fromUser;
            fromUser = CurrentSession.User;
            if (fromUser != null)
            {
                if (CurrentApplication.OnlineUsers.Contains(toUser) && CurrentApplication.OnlineUsers.Contains(fromUser))
                {
                    ChatDataAccess da = new ChatDataAccess();
                    da.InsertMessage(fromUser, toUser, message);
                }
            }
        }

        public List<ChatMess> GetMessages()
        {
            return new ChatDataAccess().GetMessage(CurrentSession.User);
        }
    }
}
